/**
 * 桥接通信主进程端初始化注册
 */
import {ipcMain, app} from 'electron';
import util from './main-util.js';

export default {
    eventNames: new Set(),
    register() {
        let dir = util.file.getAbsolutePathBasedOnRelative('./ipc-listener');
        util.file.loopDir(dir, '.*\.js', filePath => {
            import('file://' + filePath).then(module => {
                let listener = module.default;
                let eventName = listener.name;
                if (eventName && typeof listener.listen === 'function') {
                    if (this.eventNames.has(eventName.request)) {
                        console.error(`Duplicated main ipc listener: ${filePath} for '${eventName.request}'`);
                        app.exit(1);
                        return;
                    }
                    ipcMain.on(eventName.request, (event, requestId, ...args) => {
                        listener.listen(...args).then(result => {
                            event.reply(eventName.response, requestId, null, result);
                        }).catch(error => {
                            event.reply(eventName.response, requestId, error);
                        });
                    });
                    this.eventNames.add(eventName.request);
                } else {
                    console.error(`Invalid main ipc listener: ${filePath}`);
                }
            });
        });
    },
}
